package com.sf.fy.uav.applet.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sf.fy.uav.applet.user.service.AboutUserService;
import com.sf.fy.uav.common.awt.JwtUtil;
import com.sf.fy.uav.common.enums.ErrorEnum;
import com.sf.fy.uav.common.enums.MobileClientEnum;
import com.sf.fy.uav.common.enums.TaskStatusNum;
import com.sf.fy.uav.common.exception.BusinessException;
import com.sf.fy.uav.common.request.order.task.*;
import com.sf.fy.uav.common.response.IdResponse;
import com.sf.fy.uav.common.response.order.task.GoodsSoundRecordingResponse;
import com.sf.fy.uav.common.response.order.task.GoodsTypeResponse;
import com.sf.fy.uav.common.response.order.task.TaskStatusLogResponse;
import com.sf.fy.uav.common.response.user.TaskDetailResponse;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.good.controller.GoodsSoundRecordingRest;
import com.sf.fy.uav.common.utils.PhoneDesensitizationUtil;
import com.sf.fy.uav.good.entity.GoodsSoundRecording;
import com.sf.fy.uav.good.entity.GoodsType;
import com.sf.fy.uav.good.entity.TaskGoods;
import com.sf.fy.uav.good.mapper.GoodsSoundRecordingMapper;
import com.sf.fy.uav.good.mapper.GoodsTypeMapper;
import com.sf.fy.uav.good.mapper.TaskGoodsMapper;
import com.sf.fy.uav.task.controller.TaskStatusLogRest;
import com.sf.fy.uav.task.entity.Airport;
import com.sf.fy.uav.task.entity.Task;
import com.sf.fy.uav.task.entity.TaskStatusLog;
import com.sf.fy.uav.task.mapper.AirportMapper;
import com.sf.fy.uav.task.mapper.TaskMapper;
import com.sf.fy.uav.task.mapper.TaskStatusLogMapper;
import com.sf.fy.uav.task.rest.AirStationRest;
import com.sf.fy.uav.task.service.AirStationService;
import jakarta.validation.constraints.NotBlank;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LTQ
 */
@Service
public class AboutUserServiceImpl implements AboutUserService {

    private final static Logger logger = LoggerFactory.getLogger(AboutUserServiceImpl.class);
    @Autowired
    private AirStationRest airStationRest;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private TaskGoodsMapper taskGoodsMapper;

    @Autowired
    private TaskStatusLogRest taskStatusLogRest;

    @Autowired
    private GoodsSoundRecordingMapper goodsSoundRecordingMapper;

    @Autowired
    private GoodsSoundRecordingRest goodsSoundRecordingRest;

    @Autowired
    private GoodsTypeMapper goodsTypeMapper;

    @Autowired
    private AirStationService airStationService;

    @Value("${file.path:/usr/local/applet/}")
    private String baseUrl;

    @Value("${max-ing-task-num:4}")
    private String maxIngTaskNum;

    private final static String PHONE_VERIFY = "^1[0-9]{10}$";

    @Override
    public IdResponse addTask(TaskRequest taskRequest) {
        /**
         * 1.请求站点，并保存
         * 2.生成任务
         */
        Airport airport;
        IdResponse idResponse = new IdResponse();
        Date date = new Date();
        SitesRequest sitesRequest = new SitesRequest();
        sitesRequest.setLatitude(taskRequest.getLatitude().doubleValue());
        sitesRequest.setLongitude(taskRequest.getLongitude().doubleValue());
        JSONObject jsonObject = airStationRest.getAvailableDeliveryStations(sitesRequest);

        if (jsonObject.getBoolean("success")) {
            if ((Boolean) ((HashMap) jsonObject.get("obj")).get("isHasAirport")) {
                HashMap airportObj = (HashMap) ((HashMap) jsonObject.get("obj")).get("airport");
                QueryWrapper<Airport> airportQueryWrapper = new QueryWrapper<>();
                airportQueryWrapper.eq("code", airportObj.get("code"));
                airport = airportMapper.selectOne(airportQueryWrapper);
                Boolean isInsert = false;
                if (ObjectUtils.isEmpty(airport)) {
                    isInsert = true;
                    airport = new Airport();
                    airport.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    airport.setCreateTime(date);
                    airport.setCode((String) airportObj.get("code"));
                }
                airport.setUpdateTime(date);
                airport.setManagerPhone((String) airportObj.get("managerPhone"));
                airport.setManagerName((String) airportObj.get("managerName"));
                airport.setLatitude((Double) airportObj.get("latitude"));
                airport.setName((String) airportObj.get("name"));
                airport.setLongitude((Double) airportObj.get("longitude"));
                if (isInsert) {
                    airportMapper.insert(airport);
                } else {
                    airportMapper.updateById(airport);
                }
                idResponse.setId(airport.getId());
                idResponse.setName(airport.getName());
                idResponse.setLatitude((Double) airportObj.get("latitude"));
                idResponse.setLongitude((Double) airportObj.get("longitude"));
            }

        }
        return idResponse;
    }

    @Override
    public void submitTask(SubmitTaskRequest submitTaskRequest) {
        /**
         * 1.保存商品信息
         */
        String userId = JwtUtil.getUserId();
        Date date = new Date();
        QueryWrapper<Task> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.in("status", TaskStatusNum.WAIT_CONFIRM.getStatus(), TaskStatusNum.WAIT_FLY.getStatus(), TaskStatusNum.FLYING.getStatus(), TaskStatusNum.ABORT.getStatus());
        taskQueryWrapper.eq("user_id", userId);
        Long ingTaskNum = taskMapper.selectCount(taskQueryWrapper);
        if (ingTaskNum > Long.valueOf(maxIngTaskNum)) {
            throw new BusinessException(ErrorEnum.OVERSTEP);
        }
        Airport airport = airportMapper.selectById(submitTaskRequest.getAirportId());
        SubmitOrderRequest submitOrderRequest = new SubmitOrderRequest();
        submitOrderRequest.setSource(MobileClientEnum.WECHAT_APPLET.getCode());
        GoodsType goodsType = goodsTypeMapper.selectById(submitTaskRequest.getGoodsTypeId());
        if (!ObjectUtils.isEmpty(goodsType)) {
            submitOrderRequest.setGoodsType(goodsType.getCode());
        }

        submitOrderRequest.setGoodsInfo(submitTaskRequest.getGoodsName());
        if (!ObjectUtils.isEmpty(airport)) {
            submitOrderRequest.setDeliveryCode(airport.getCode());
        }
        submitOrderRequest.setDestLon(submitTaskRequest.getLongitude().doubleValue());
        submitOrderRequest.setDestLat(submitTaskRequest.getLatitude().doubleValue());
        submitOrderRequest.setRevicePhone(phoneHandle(submitTaskRequest.getPhoneCode(),submitTaskRequest.getPhoneNum()));
        submitOrderRequest.setAddress(submitTaskRequest.getAddress());
        if(StringUtils.isNotBlank(submitTaskRequest.getContactName())){
            submitOrderRequest.setReviceName(submitTaskRequest.getContactName());
        }
        if(!ObjectUtils.isEmpty(submitTaskRequest.getAltitude())){
            submitOrderRequest.setDestAlt(submitTaskRequest.getAltitude());
        }
        List<GoodsSoundRecording> goodsSoundRecordings = goodsSoundRecordingRest.selectListByTaskId(submitTaskRequest.getId());
//        String fileSavePath = baseUrl + "goods/record/";
      String fileSavePath = "https://ie-uocs-out.sit.sf-express.com:4433/uocs-rescue/"+baseUrl;
        if (!CollectionUtils.isEmpty(goodsSoundRecordings)) {
            submitOrderRequest.setVoices(goodsSoundRecordings.stream().map(goodsSoundRecording -> fileSavePath + goodsSoundRecording.getFileName()).collect(Collectors.toList()));
        }

        JSONObject jsonObject = airStationRest.submitOrder(submitOrderRequest);


        if (jsonObject.getBoolean("success")) {
            String orderCode = jsonObject.getJSONObject("obj").getString("orderCode");
            Task task = BeanUtil.copyProperties(submitTaskRequest, Task.class);
            task.setId(submitTaskRequest.getId());
            task.setAirportId(submitTaskRequest.getAirportId());
            task.setStatus(TaskStatusNum.WAIT_CONFIRM.getStatus());
            task.setUserId(userId);
            task.setCreateTime(date);
            task.setUpdateTime(date);
            task.setOrderCode(orderCode);
            taskMapper.insert(task);

            TaskStatusLog taskStatusLog = new TaskStatusLog();
            taskStatusLog.setStatus(task.getStatus());
            taskStatusLog.setTaskId(task.getId());
            taskStatusLog.setCreateTime(date);
            taskStatusLog.setUpdateTime(date);
            taskStatusLogRest.add(taskStatusLog);


            TaskGoods taskGoods = new TaskGoods();
            taskGoods.setTaskId(task.getId());
            taskGoods.setGoodsTypeId(submitTaskRequest.getGoodsTypeId());
            taskGoods.setName(submitTaskRequest.getGoodsName());
            taskGoods.setCreateTime(date);
            taskGoods.setUpdateTime(date);
            taskGoodsMapper.insert(taskGoods);

            List<GoodsSoundRecordingRequest> goodsSoundRecordingRequests = submitTaskRequest.getGoodsSoundRecordingRequests();
            if (!CollectionUtils.isEmpty(goodsSoundRecordingRequests)) {
                goodsSoundRecordingRequests.forEach(goodsSoundRecordingRequest -> {
                    GoodsSoundRecording goodsSoundRecording = BeanUtil.copyProperties(goodsSoundRecordingRequest, GoodsSoundRecording.class);
                    goodsSoundRecording.setTaskId(task.getId());
                    goodsSoundRecordingMapper.insert(goodsSoundRecording);
                });
            }

        } else {
            logger.info(jsonObject.getString("errorMessage"));
            throw new BusinessException(ErrorEnum.ERR_CLIENT_PARAM, "添加任务失败");
        }
    }

    @Override
    public JSONObject getOrderInfo(String orderCode) {
        JSONObject jsonObject = airStationRest.getOrderInfo(orderCode);
        return jsonObject;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelTask(String id) {
        Date date = new Date();
        Task task = taskMapper.selectById(id);
        if (ObjectUtils.isEmpty(task)) {
            throw new RuntimeException("任务不存在");
        } else {
            if (!task.getStatus().equals(TaskStatusNum.WAIT_CONFIRM.getStatus())
//                    && !task.getStatus().equals(TaskStatusNum.WAIT_FLY.getStatus())
            ){
                throw new BusinessException(ErrorEnum.NOT_WAIT_CONFIRM);
            }
        }

        UpdateOrderStatusRequest updateOrderStatusRequest = new UpdateOrderStatusRequest();
        updateOrderStatusRequest.setOrderCode(task.getOrderCode());
        updateOrderStatusRequest.setStatus(TaskStatusNum.CANCEL.getStatus());
        JSONObject jsonObject = airStationService.updateOrderStatus(updateOrderStatusRequest);
        if (jsonObject.getBoolean("success")) {
            task.setStatus(TaskStatusNum.CANCEL.getStatus());
            task.setUpdateTime(new Date());
            taskMapper.updateById(task);
        }
        System.out.println("");
    }

    @Override
    public TaskDetailResponse getTaskDetail(String id) {
        Date date = new Date();
        Task task = taskMapper.selectById(id);
        if (ObjectUtils.isEmpty(task)) {
            throw new RuntimeException("任务不存在");
        }
        TaskDetailResponse taskDetailResponse = BeanUtil.copyProperties(task, TaskDetailResponse.class);
        taskDetailResponse.setPhoneNum(phoneDispose(task.getPhoneCode(),task.getPhoneNum()));
        QueryWrapper<TaskGoods> taskGoodsQueryWrapper = new QueryWrapper<>();
        taskGoodsQueryWrapper.eq("task_id", task.getId());
        //获取商品信息
        TaskGoods taskGoods = taskGoodsMapper.selectOne(taskGoodsQueryWrapper);
        Airport airport = airportMapper.selectById(task.getAirportId());
        if (!ObjectUtils.isEmpty(taskGoods)) {
            GoodsType goodsType = goodsTypeMapper.selectById(taskGoods.getGoodsTypeId());
            GoodsTypeResponse goodsTypeResponse = BeanUtil.copyProperties(taskGoods, GoodsTypeResponse.class);
            goodsTypeResponse.setGoodsTypeName(goodsType.getName());
            goodsTypeResponse.setGoodsTypeId(goodsType.getId());
            taskDetailResponse.setGoodsTypeResponse(goodsTypeResponse);
        }
        if (!ObjectUtils.isEmpty(airport)) {
            taskDetailResponse.setAirportName(airport.getName());
            taskDetailResponse.setAirLatitude(airport.getLatitude());
            taskDetailResponse.setAirLongitude(airport.getLongitude());
        }
        List<GoodsSoundRecording> goodsSoundRecordings = goodsSoundRecordingRest.selectListByTaskId(id);
        if(!CollectionUtils.isEmpty(goodsSoundRecordings)){
            taskDetailResponse.setRecordArr(BeanUtil.copyProperties(goodsSoundRecordings, GoodsSoundRecordingResponse.class));
        }
        //获取订单最新信息
        JSONObject jsonObject = airStationRest.getOrderInfo(task.getOrderCode());
        if (jsonObject.getBoolean("success")) {
            //更新任务状态
            Integer status = jsonObject.getJSONObject("obj").getInteger("status");
            String uavType = jsonObject.getJSONObject("obj").getString("uavType");
            if (!ObjectUtils.isEmpty(uavType)) {
                task.setUavType(uavType);
                taskDetailResponse.setUavType(uavType);
            }
            HashMap position = (HashMap) ((HashMap) jsonObject.get("obj")).get("position");
            ArrayList allRouteLocation = (ArrayList) ((HashMap) jsonObject.get("obj")).get("allRouteLocation");
            taskDetailResponse.setPosition(position);
            taskDetailResponse.setAllRouteLocation(allRouteLocation);
            if (!status.equals(task.getStatus())) {
                taskDetailResponse.setStatus(status);
                task.setStatus(status);
                task.setUpdateTime(date);
                taskMapper.updateById(task);
                TaskStatusLog taskStatusLog = new TaskStatusLog();
                taskStatusLog.setStatus(task.getStatus());
                taskStatusLog.setTaskId(task.getId());
                taskStatusLog.setCreateTime(date);
                taskStatusLog.setUpdateTime(date);
                taskStatusLogRest.add(taskStatusLog);
            }
        }
        return taskDetailResponse;
    }

    @Override
    public List<TaskStatusLogResponse> getTaskStatusLog(String taskId) {
        List<TaskStatusLog> taskStatusLogs = taskStatusLogRest.selectListByTaskId(taskId);
        List<TaskStatusLogResponse> taskStatusLogResponses = BeanUtil.copyProperties(taskStatusLogs, TaskStatusLogResponse.class);
        return taskStatusLogResponses;
    }

    @Override
    public List<GoodsSoundRecordingResponse> getGoodsSoundRecording(String taskId) {
        List<GoodsSoundRecording> goodsSoundRecordings = goodsSoundRecordingRest.selectListByTaskId(taskId);
        return BeanUtil.copyProperties(goodsSoundRecordings, GoodsSoundRecordingResponse.class);
    }

    @Override
    public void updateGoods(TaskGoodsRequest taskGoodsRequest) {
        QueryWrapper<TaskGoods> taskGoodsQueryWrapper = new QueryWrapper<>();
        taskGoodsQueryWrapper.eq("task_id", taskGoodsRequest.getTaskId());
        TaskGoods taskGoods = taskGoodsMapper.selectOne(taskGoodsQueryWrapper);
        if (!ObjectUtils.isEmpty(taskGoods)) {

            UpdateOrderRequest updateOrderRequest = new UpdateOrderRequest();
            Task task = taskMapper.selectById(taskGoodsRequest.getTaskId());
            if (!task.getStatus().equals(TaskStatusNum.WAIT_CONFIRM.getStatus())) {
                throw new BusinessException(ErrorEnum.NOT_WAIT_CONFIRM);
            }
            taskGoods.setGoodsTypeId(taskGoodsRequest.getGoodsTypeId());
            taskGoods.setName(taskGoodsRequest.getGoodsName());
            taskGoods.setUpdateTime(new Date());
            taskGoodsMapper.updateById(taskGoods);

            if (!ObjectUtils.isEmpty(task)) {
                updateOrderRequest.setOrderCode(task.getOrderCode());
            }
            GoodsType goodsType = goodsTypeMapper.selectById(taskGoodsRequest.getGoodsTypeId());
            if (!ObjectUtils.isEmpty(goodsType)) {
                updateOrderRequest.setGoodsType(goodsType.getCode());
            }
            if(StringUtils.isNotBlank(taskGoodsRequest.getContactName())){
                updateOrderRequest.setReviceName(taskGoodsRequest.getContactName());
            }
            updateOrderRequest.setGoodsInfo(taskGoodsRequest.getGoodsName());
            JSONObject jsonObject = airStationRest.modifyOrder(updateOrderRequest);
            if (!jsonObject.getBoolean("success")) {
                throw new RuntimeException(jsonObject.get("errorMessage").toString());
            }
        }
    }
    private String phoneDispose(String phoneCode,String phoneNum){
        if(!ObjectUtils.isEmpty(phoneCode) && !ObjectUtils.isEmpty(phoneNum) && !phoneNum.matches(PHONE_VERIFY)){
            return phoneCode + "-" + phoneNum;
        }
        if(ObjectUtils.isEmpty(phoneCode) && !ObjectUtils.isEmpty(phoneNum) && phoneNum.matches(PHONE_VERIFY)){
           return PhoneDesensitizationUtil.phoneDesensitization(phoneNum);
        }
        return null;
    }
    private String phoneHandle(String phoneCode,String phoneNum){
        if(!ObjectUtils.isEmpty(phoneCode) && !ObjectUtils.isEmpty(phoneNum) && !phoneNum.matches(PHONE_VERIFY)){
            return phoneCode + "-" + phoneNum;
        }
        if(ObjectUtils.isEmpty(phoneCode) && !ObjectUtils.isEmpty(phoneNum) && phoneNum.matches(PHONE_VERIFY)){
            return phoneNum;
        }
        return null;
    }
}
